package auth

import (
	"fmt"
	"grpc.getaway.adminspro.padmins.com/internal/api/module/admin/container"
	"grpc.getaway.adminspro.padmins.com/internal/api/utils/rpc"
	pbAuthorizationAdmin "grpc.getaway.adminspro.padmins.com/pkg/proto/authorizationAdmin"
	"net/http"
)

func Login(c *container.Context) (interface{}, error) {

	req := &pbAuthorizationAdmin.LoginReq{
		Account:  c.Request.ParamsToString("account"),
		Password: c.Request.ParamsToString("password"),
	}

	RpcResp, err := rpc.GetAuthorizationAdminClient().Login(c.GetContext(), req)

	if err != nil {
		return nil, err
	}

	Cookie := &http.Cookie{
		Name:     "token",
		Value:    fmt.Sprintf("%d-%s", RpcResp.Admin.Id, RpcResp.Admin.Token),
		MaxAge:   0,
		Domain:   "",
		Path:     "/",
		Secure:   false,
		HttpOnly: false,
	}

	c.Response.HeaderAdd("Set-Cookie", Cookie.String())

	return map[string]map[string]string{
		"admin": {
			"token": fmt.Sprintf("%d-%s", RpcResp.Admin.Id, RpcResp.Admin.Token),
		},
	}, nil
}
